package com.starblink.android.basic.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.starblink.android.basic.BuildConfig;
import com.starblink.android.basic.R;
import com.starblink.basic.log.SKLogger;
import com.starblink.basic.log.report.ErrorReporter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;


/**
 * 对话框 Loading
 */
public class LoadingDialogManager {

    private static LoadingDialogManager ourInstance = new LoadingDialogManager();
    private Dialog mDialog;
    private Dialog mProgressDialog;

    public static LoadingDialogManager get() {
        return ourInstance;
    }

    private LoadingDialogManager() {
    }

    public boolean isShowing() {
        if (mDialog == null) {
            return false;
        }
        return mDialog.isShowing();
    }

    /**
     * 展示dialog
     */
    public void showLoading(Activity activity) {
        try {
            if (mDialog != null && mDialog.isShowing()) {
                return;
            }
            if (activity instanceof LifecycleOwner) {
                Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
                Lifecycle.State state = lifecycle.getCurrentState();
                lifecycle.addObserver(new LifecycleEventObserver() {
                    @Override
                    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                        lifecycle.removeObserver(this);
                        if (event == Lifecycle.Event.ON_DESTROY) {
                            mDialog.dismiss();
                            mDialog = null;
                        }
                    }
                });
                if (state == Lifecycle.State.DESTROYED) {
                    return;
                }
            }

            mDialog = new AppCompatDialog(activity, R.style.Theme_LoadingDialog);
            //自定义布局
            View view = LayoutInflater.from(activity).inflate(com.starblink.basic.style.R.layout.base_layout_loading, null);
            mDialog.setContentView(view);
            //一定要先show出来再设置dialog的参数，不然就不会改变dialog的大小了
            mDialog.setCancelable(true);
            mDialog.setCanceledOnTouchOutside(false);

            mDialog.setOnCancelListener(dialog -> {
                if (mListener != null) {
                    mListener.onLoadingCancel();
                }
            });

            mDialog.show();
            // TODO fix, each activity own a dialog
        } catch (Throwable throwable) {
            if (BuildConfig.DEBUG) {
//                throw throwable;
                SKLogger.e("ShowLoading", throwable.toString());
            } else {
                ErrorReporter.INSTANCE.report(throwable);
            }
        }
    }

    /**
     * 展示H5loading dialog
     */
    public void showH5Loading(Activity activity) {
        if (mDialog != null && mDialog.isShowing()) {
            return;
        }
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            Lifecycle.State state = lifecycle.getCurrentState();
            lifecycle.addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                    lifecycle.removeObserver(this);
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        mDialog.dismiss();
                    }
                }
            });
            if (state == Lifecycle.State.DESTROYED) {
                return;
            }
        }

        mDialog = new AppCompatDialog(activity, R.style.Theme_LoadingDialog);
        //自定义布局
        View view = LayoutInflater.from(activity).inflate(com.starblink.basic.style.R.layout.base_layout_h5loading, null);
        mDialog.setContentView(view);
        //一定要先show出来再设置dialog的参数，不然就不会改变dialog的大小了
        mDialog.setCancelable(true);
        mDialog.setCanceledOnTouchOutside(false);

        mDialog.setOnCancelListener(dialog -> {
            if (mListener != null) {
                mListener.onLoadingCancel();
            }
        });

        mDialog.show();

        Window win = mDialog.getWindow();
        //实现Dialog区域外部事件可以传给Activity
        //FLAG_NOT_TOUCH_MODAL作用：即使该window可获得焦点情况下，仍把该window之外的任何event发送到该window之后的其他window
        win.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        //FLAG_WATCH_OUTSIDE_TOUCH作用：如果点击事件发生在window之外，就会收到一个特殊的MotionEvent，为ACTION_OUTSIDE
        win.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
    }

    /**
     * 展示长条的大Dialog
     */
    public void showBigLoading(Activity activity) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            return;
        }
        mProgressDialog = new Dialog(activity, R.style.Theme_LoadingDialog);
        //自定义布局
        View view = LayoutInflater.from(activity).inflate(com.starblink.basic.style.R.layout.base_layout_uploading_progress, null);
        mProgressDialog.setContentView(view);
        //一定要先show出来再设置dialog的参数，不然就不会改变dialog的大小了
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);

        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mListener != null) {
                    mListener.onLoadingCancel();
                }
            }
        });

        mProgressDialog.show();
    }

    /**
     * 隐藏dialog
     */
    public void dismissLoading() {
//        SKLogger.e("dss", "dismissLoading");
        try {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
                mDialog.cancel();
            }
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog.cancel();
            }
            // TODO fix, each activity own a dialog
        } catch (Throwable e) {
            if (BuildConfig.DEBUG) {
//                throw e;
                SKLogger.e("ShowLoading", e.toString());
            } else {
                ErrorReporter.INSTANCE.report(e);
            }

        }
    }

    private OnLoadingCancelListener mListener;

    public void SetOnLoadingCancelListener(OnLoadingCancelListener listener) {
        this.mListener = listener;
    }

    public interface OnLoadingCancelListener {

        void onLoadingCancel();
    }

}
